#!/bin/bash
# tary, 15:58 2019-06-03

# set -x;

. $(dirname $0)/gpio

SYS_GPIO_DIR="/sys/class/gpio"

[ "$#" -eq 0 -o "$1" == "-h" -o "$1" == "--help" ] && {
	echo "Usage"
	echo "  $0 GPIO1A,GPIO1B GPIO2A,GPIO2B ...";
	exit 1;
}

# display_fifo=${TMPDIR:-"/tmp"}/common_test_fifo
# display_cpuinfo='0'
display_echo=
display_result=

display_message() {
	local msg="$1$2"
	# echo $msg > $display_fifo
	echo $msg
}

field_get() {
	local delim=$1
	local line=$2
	local index=$3

	set `echo $line | tr \'$delim\' ' '`
	eval val=\$$index
	echo $val
}

connection_test() {
	local out=$1
	local in=$2
	local v

	echo 0 > $out
	sleep 0.01
	v=$(cat $in)
	[ $v != 0 ] && { return 1; }

	echo 1 > $out
	sleep 0.01
	v=$(cat $in)
	[ $v != 1 ] && { return 1; }
	
	return 0;
}

pairs_test() {
	local ga=$1
	local gb=$2
	local ers="$ga,$gb "

	[ ! -e gpio$ga/direction -o ! -e gpio$gb/direction ] && {
		# echo "1#"
		echo -ne "$ers"
		return 1;

	}

	echo out > gpio$ga/direction
	echo in > gpio$gb/direction
	connection_test gpio$ga/value gpio$gb/value || {
		# echo "2#"
		echo -ne "$ers"
		return 1;
	}

	echo out > gpio$gb/direction
	echo in > gpio$ga/direction
	connection_test gpio$gb/value gpio$ga/value || {
		# echo "3#"
		echo -ne "$ers"
		return 1;
	}
	return 0;
}

LAST_DIR=`pwd`
cd $SYS_GPIO_DIR
error_groups=""


# put all gpios into input mode
for i in $@; do
	gpa=$(field_get ',' $i 1)
	gpb=$(field_get ',' $i 2)
	# echo gpioa=$gpa gpiob=$gpb

	gpio input $gpa
	gpio input $gpb
done > /dev/null


# display_message $display_result "gpio pairs scanning, unconnected pairs list:"

for i in $@; do
	gpa=$(field_get ',' $i 1)
	gpb=$(field_get ',' $i 2)
	# echo gpioa=$gpa gpiob=$gpb

	echo $gpa > unexport
	echo $gpb > unexport
	echo $gpa > export
	echo $gpb > export

	error_groups="${error_groups}$(pairs_test $gpa $gpb)"
	[ "X$error_groups" != "X" ] && {
		true # display_message $display_result "$error_groups"
	}

	{
	gpio input $gpa
	gpio input $gpb
	} > /dev/null
done

# echo "#error groups = '${error_groups}'"

[ "X$error_groups" != "X" ] && {
	display_message $display_result "$error_groups"
	# sleep 5
	exit 1;
}

echo "$0: Version GPIO multiple group"
display_message $display_echo " "
cd $LAST_DIR
exit 0
